package com.sgb.kjwl.view.ui.activity.packers;

import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityTeamInviteJoinBinding;
import com.sgb.kjwl.model.entity.packers.InviteCompanyEntity;
import com.sgb.kjwl.model.entity.packers.MyCompanyEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.view.ui.adapter.self.packers.CargoCustomValueForTeamAdapter;
import com.sgb.kjwl.viewmodel.packers.TeamInviteJoinModel;
import com.sgb.link.router.PathTeam;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickerHelper;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: 王彬臣
 * @date: 2021/9/6
 * @Description: 工队邀请加盟
 */
@Route(path = PathTeam.TeamInviteJoinActivity)
public class TeamInviteJoinActivity extends BaseActivity<TeamInviteJoinModel, ActivityTeamInviteJoinBinding> implements ItemInputTextView.OnWholeItemClickListener{
    @Autowired(name = RouterKey.NO,desc = "公司no")
    String no;
    @Autowired(name = RouterKey.NAME,desc = "公司名")
    String name;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueForTeamAdapter mCustomAdapter;
    InviteCompanyEntity mEntity;
    List<CommonPopEntity> levelList;
    private OptionsPickerView<CommonPopEntity> levelPicker;
    List<CommonPopEntity> typeList;
    private OptionsPickerView<CommonPopEntity> typePicker;
    List<CommonPopEntity> serviceList;
    private OptionsPickerView<CommonPopEntity> servicePicker;
    List<MyCompanyEntity> companyList;
    private OptionsPickerView<MyCompanyEntity> companyPicker;
    private int mCompanyType;
    String myCompanyNo,myCompanyName;
    private List<CommonPopEntity> supplyList;
    private OptionsPickerView<CommonPopEntity> supplyPicker;
    @Override
    protected int layoutId() {
        return R.layout.activity_team_invite_join;
    }

    @Override
    protected void createViewModel() {
       mViewModel=new ViewModelProvider(this).get(TeamInviteJoinModel.class);
    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setOnClick(this);
        mBinding.itemMyCompany.setOnWholeItemClickListener(this);
        mBinding.itemLeve.setOnWholeItemClickListener(this);
        mBinding.itemType.setOnWholeItemClickListener(this);
        mBinding.itemSupply.setOnWholeItemClickListener(this);
        mBinding.itemCollaborateType.setOnWholeItemClickListener(this);
        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueForTeamAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCargoOrdersField);
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);
        initSupplyPick();
        initEvent();
        initData();

    }

    private void initData() {
        mEntity=new InviteCompanyEntity();
        mBinding.itemApplyCompany.setContent(name);
        mViewModel.ldLevel.observe(this,data->{
            levelList=data;
            if(levelList.size()>0){
                if ("全部".equals(levelList.get(0).getTypeName())) {
                    levelList.remove(0);
                }
                initLevelPick();
                levelPicker.show();
            }

        });
        mViewModel.ldType.observe(this,data->{
            typeList=data;
            initTypePick();
            typePicker.show();
        });
        mViewModel.ldService.observe(this,data->{
            serviceList=data;
            initServicePick();
            servicePicker.show();
        });
        mViewModel.ldCompany.observe(this,data->{
            companyList=data;
            initCompanyPick();
            companyPicker.show();
        });
        mViewModel.ldResult.observe(this,result->{
            if(result){
                finish();
            }
        });
        mCompanyType = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        myCompanyName=SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME,"");
        if(mCompanyType==1){
            mBinding.itemMyCompany.setContent(myCompanyName);
            mEntity.setCompanyNo(myCompanyNo);
            mEntity.setCompanyName(myCompanyName);
        }
        mEntity.setApplyCompanyName(name);
        mEntity.setApplyCompanyNo(no);

    }

    private void initEvent() {
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
                if(mCustomList.size()==0){
                    mBinding.rvCargoOrdersField.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initServicePick() {
        servicePicker= PickerHelper.with(this).getCommonPicker("选择合作类型",serviceList,new OnOptionsSelectListener(){
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonPopEntity unitEntity=serviceList.get(options1);
                mBinding.itemCollaborateType.setContent(unitEntity.getTypeName(),13);
                mEntity.setCooperateType(unitEntity.getId());
            }
        });
    }

    private void initTypePick() {
        typePicker= PickerHelper.with(this).getCommonPicker("选择会员类型",typeList,new OnOptionsSelectListener(){
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonPopEntity unitEntity=typeList.get(options1);
                mBinding.itemType.setContent(unitEntity.getTypeName());
                mEntity.setMemberType(unitEntity.getNo());
            }
        });
    }

    public void initLevelPick(){
        levelPicker= PickerHelper.with(this).getCommonPicker("选择会员等级",levelList,new OnOptionsSelectListener(){
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonPopEntity unitEntity=levelList.get(options1);
                mBinding.itemLeve.setContent(unitEntity.getTypeName());
                mEntity.setLevel(unitEntity.getTypeName());
            }
        });
    }

    public void initCompanyPick(){
        companyPicker= PickerHelper.with(this).getCommonPicker("选择我的单位",companyList,new OnOptionsSelectListener(){
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                MyCompanyEntity myCompanyEntity=companyList.get(options1);
                mBinding.itemMyCompany.setContent(myCompanyEntity.getName());
                mEntity.setCompanyName(myCompanyEntity.getName());
                mEntity.setCompanyNo(myCompanyEntity.getNo());
            }
        });
    }
    public void initSupplyPick(){
        supplyList = new ArrayList<>();
        supplyList.add(new CommonPopEntity("1", "供方会员"));
        supplyList.add(new CommonPopEntity("2", "需方会员"));
        supplyPicker= PickerHelper.with(this).getCommonPicker("选择供需关系",supplyList,new OnOptionsSelectListener(){
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonPopEntity myCompanyEntity=supplyList.get(options1);
                mBinding.itemSupply.setContent(myCompanyEntity.getTypeName());
                mEntity.setRelation(myCompanyEntity.getNo());
            }
        });

    }

    @Override
    public void OnWholeItemClick(View view) {
        if(view.getId()==R.id.item_my_company){
            if(mViewModel.ldCompany.getValue()!=null&&mViewModel.ldCompany.getValue().size()>0){
                companyPicker.show();
            }else{
                mViewModel.getCompany();
            }
        }else if(view.getId()==R.id.item_leve){
            if(mViewModel.ldLevel.getValue()!=null&&mViewModel.ldLevel.getValue().size()>0){
                levelPicker.show();

            }else{
                mViewModel.getMemberLevels();
            }

        }else if(view.getId()==R.id.item_type){
            if(mViewModel.ldType.getValue()!=null&&mViewModel.ldType.getValue().size()>0){
                typePicker.show();

            }else{
                mViewModel.getMemberType();
            }
        }else if(view.getId()==R.id.item_supply){
            supplyPicker.show();
        }else if(view.getId()==R.id.item_collaborate_type){
            if(mViewModel.ldService.getValue()!=null&&mViewModel.ldService.getValue().size()>0){
                servicePicker.show();
            }else{
                mViewModel.getServiceType();
            }
        }
    }
    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 5) {
            MToast.showToast(this, "最多只能新增五个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
        if(mBinding.rvCargoOrdersField.getVisibility()==View.GONE){
            mBinding.rvCargoOrdersField.setVisibility(View.VISIBLE);
        }

    }
    /**
     * 检查自定义字段
     */
    private boolean loadFieldData() {
        List<InviteCompanyEntity.ParamDtosBean> paramBeans=new ArrayList<>();
        if (mCustomList != null && !mCustomList.isEmpty()) {
            Set<String> fieldName = new HashSet<>();
            //判断是否填写了自定义字段
            for (SingleItemEntity entity : mCustomList) {
                if (!fieldName.contains(entity.getLeftString())) {
                    fieldName.add(entity.getLeftString());
                } else {
                    MToast.showToast(this, "请检查新增字段名称是否有重复");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getLeftString())) {
                    MToast.showToast(this, "有新增的标题和内容未填写");
                    return false;
                }
                if (TextUtils.isEmpty(entity.getRightString())) {
                    MToast.showToast(this, "有新增的标题和内容未填写");
                    return false;
                }
            }

            for (SingleItemEntity diy : mCustomList) {
                InviteCompanyEntity.ParamDtosBean data=new InviteCompanyEntity.ParamDtosBean();
                data.setTitle(diy.getLeftString());
                data.setContent(diy.getRightString());
                paramBeans.add(data);
            }
        }
        mEntity.setParamDtos(paramBeans);
        return true;
    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.submit){
            if(ClickUtils.isDoubleClick()){
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemMyCompany.getContent())){
                MToast.showToast(this,"请选择我的单位");
                return;
            }
            if(mEntity.getCompanyNo().equals(no)){
                MToast.showToast(this,"不能邀请加盟自己的企业");
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemLinkName.getContent())){
                MToast.showToast(this,"请输入联系人");
                return;
            }else if(mBinding.itemLinkName.getContent().length()<2){
                MToast.showToast(this,"联系人信息字段长度不能少于两位");
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemLinkPhone.getContent())){
                MToast.showToast(this,"请输入联系电话");
                return;
            }else if(!CheckUtils.checkMobile(mBinding.itemLinkPhone.getContent())){
                MToast.showToast(this,"请输入正确联系电话");
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemCollaborateType.getContent())){
                MToast.showToast(this,"请选择合作类型");
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemSupply.getContent())){
                MToast.showToast(this,"请选择供需关系");
                return;
            }

            if (!loadFieldData()) {
                return;
            }

            if(TextUtils.isEmpty(mBinding.itemLeve.getContent())){
                MToast.showToast(this,"请选择会员等级");
                return;
            }
            if(TextUtils.isEmpty(mBinding.itemType.getContent())){
                MToast.showToast(this,"请选择会员类型");
                return;
            }

            mEntity.setContacts(mBinding.itemLinkName.getContent());
            mEntity.setPhone(mBinding.itemLinkPhone.getContent());
            DialogHelper.showProgressDialog(this, "加载中").setCanceledOnTouchOutside(true);
            mViewModel.invite(mEntity);


        }else if(v.getId()==R.id.tv_cargo_orders_add){
            addField();
        }
    }
}
